package com.zl_huang.example.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zl_huang.example.dao.ISubjectDaoHibernate;
import com.zl_huang.example.model.Subject;
@Service
public class SubjectServiceImp implements ISubjectService {
	@Autowired
	private ISubjectDaoHibernate subjectDaoHibernate;

	@Override
	public Integer createSubject(Subject subject) throws Exception {
		return subjectDaoHibernate.createSubject(subject);
	}

	@Override
	public Integer editSubject(Subject subject) throws Exception {
		return subjectDaoHibernate.editSubject(subject);
	}

	@Override
	public Integer deleteSubject(int sub_id) throws Exception {
		return subjectDaoHibernate.deleteSubject(sub_id);
	}

	@Override
	public List<Subject> findAllSubject() throws Exception {
		return subjectDaoHibernate.findAllSubject();
	}

	@Override
	public Subject getSubjectById(int sub_id) throws Exception {
		return subjectDaoHibernate.getSubjectById(sub_id);
	}

	@Override
	public List<String> getAllUserBySubId(Integer sub_id) throws Exception {
		
		return subjectDaoHibernate.getAllUserBySubId(sub_id);
	}

	@Override
	public void saveSubjectStudent(List<String> list, Integer sub_id) throws Exception {		
		List<String> dbSubjectUserList = subjectDaoHibernate.getAllUserBySubId(sub_id);
		for(String selectedUser : dbSubjectUserList){
			System.out.println("数据库取出来的数据是"+selectedUser);
		}
		List<String> insertList = new ArrayList<String>();
		List<String> delList = new ArrayList<String>();
		//判断那些学生是新勾选上的
	   for(String selectedUser : list){		 
		   System.out.println("从页面传过了的数据是"+selectedUser);
	    	if(!dbSubjectUserList.contains(selectedUser)){
	    		System.out.println("排除掉数据库已经有的，最新添加的数据是"+selectedUser);
	    		insertList.add(selectedUser);
	    	}
	    }
	  for(int i = 0;i < list.size(); i++){
		  
	  }
	    //判断哪些学生本来是被勾选上的，现在去掉勾选了的
	   for(String selectedUser : dbSubjectUserList){
		   if(!list.contains(selectedUser)){
			   System.out.println("去掉放弃勾选的"+selectedUser);
			   delList.add(selectedUser);
		   }
	   }
	   //保存那些新勾选上的学生
	   subjectDaoHibernate.insertSubjectUsers(insertList,sub_id);
	   //删除那些本来已经勾选上的，现在去掉勾选的额
	   subjectDaoHibernate.deleteSubjectUsers(delList,sub_id);
	   
		
	}

}
